<?php

namespace App\Http\Resources;

use App\Models\Books;
use App\Models\BookScore;
use App\Models\BookType;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;

class BooksResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $str = ['new/list'];//排除字段
        return [
            'id' => $this->id,
            'name' => $this->name,
            'cover' => $this->cover,
            'intro' => $this->intro,
            'view_num' => $this->view_num,
            'like_num' => $this->like_num,
            'comment_num' => $this->comment_num,
            'share_num' => $this->share_num,
            'module_id' => $this->module_id,
            'module_name' => Books::MODULE_ID[$this->module_id],
            'collect_num' => $this->collect_num,
            'is_top' => $this->is_top,
            'status' => (int)$this->status,
            'type_name' => BookType::whereIn('id', explode(',', $this->type_id))->pluck('name'),
            'user' => new UserResource($this->whenLoaded('user')),
            'score' => (int)BookScore::where('book_id', $this->id)->avg('score'),
        ];
    }
}
